"""对话生成服务"""
from typing import List, Dict, AsyncGenerator
from openai import AsyncOpenAI
from app.core.config import settings


class ChatService:
    """对话生成服务"""
    
    def __init__(self):
        """初始化 OpenAI 客户端"""
        self.client = AsyncOpenAI(
            api_key=settings.OPENAI_API_KEY,
            base_url=settings.OPENAI_BASE_URL
        )
        self.model = settings.CHAT_MODEL
    
    async def generate_answer_stream(
        self,
        question: str,
        context: List[str]
    ) -> AsyncGenerator[str, None]:
        """
        流式生成回答
        
        Args:
            question: 用户问题
            context: 上下文文本块列表
            
        Yields:
            生成的文本片段
        """
        # 构建系统提示
        context_text = "\n\n".join([f"片段 {i+1}:\n{chunk}" for i, chunk in enumerate(context)])
        
        system_message = f"""你是一个智能助手，基于提供的文档片段回答用户的问题。

文档片段：
{context_text}

请仔细阅读以上文档片段，然后根据这些内容回答用户的问题。如果文档中没有相关信息，请诚实地告诉用户。"""
        
        messages = [
            {"role": "system", "content": system_message},
            {"role": "user", "content": question}
        ]
        
        # 流式调用 OpenAI API
        stream = await self.client.chat.completions.create(
            model=self.model,
            messages=messages,
            stream=True
        )
        
        async for chunk in stream:
            if chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content

